package org.pms.servlet;

import com.google.gson.Gson;
import org.pms.dao.ProductDao;
import org.pms.dao.impl.ProductDaoImpl;
import org.pms.dto.ResultDto;
import org.pms.entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Map;

@WebServlet("/api/product_update.do")
public class UpdateProductServlet extends BaseServlet {
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.获取客户端传递的参数数据
        Map<String, String> map = parseMap(req);
        String id = map.get("id");
        String name = URLDecoder.decode(map.get("name"),"UTF-8");
        double price = Double.parseDouble(map.get("price"));
        int count = Integer.parseInt(map.get("count"));
        String image = map.get("image") ;
        String desc = URLDecoder.decode(map.get("desc"),"UTF-8");

        Product p = new Product(id,name,price,count,image,desc) ;

        // 2. 对数据进行处理（格式） -- 先封装到DTO对象中，后再序列为JSON字符串
        ProductDao productDao = new ProductDaoImpl();
        int row = productDao.update(p) ;

        // 3.响应数据到客户端浏览器中
        ResultDto dto =successJson() ;
        if(row!=1) {
            dto = errorJson("修改商品失败") ;
        }
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.print(new Gson().toJson(dto));
        out.flush();
        out.close();
    }
}
